package com.FH.applyFrom.report_to_repair;

import com.FH.organization.department.DepartmentResource;
import com.FH.organization.logistics_dispatch.LogisticsDispatchResource;
import com.FH.organization.operator_log.OperatorLogPullDTO;
import com.FH.organization.operator_log.OperatorLogResource;
import com.FH.organization.people.KamMemberResource;

import com.FH.organization.repair_type.RepairTypeResource;
import com.FH.organization.suggestion.SuggestionResource;
import com.FH.organization.work_flow.WorkFlowPullDTO;
import com.FH.organization.work_flow.WorkFlowResource;
import com.FH.util.*;
import com.itextpdf.text.DocumentException;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/12/16.
 */
@Stateless
public class ReportToReapairImpl extends AccessDB implements ReportToRepairDAO {
    @Inject
    KamMemberResource kamMemberResource;
    @Inject
    OperatorLogResource operatorLogResource;
    @Inject
    DepartmentResource departmentResource;
    @Inject
    WorkFlowResource workFlowResource;
    @Inject
    SuggestionResource suggestionResource;
    @Inject
    RepairTypeResource repairTypeResource;
    @Inject
    LogisticsDispatchResource logisticsDispatchResource;

    @Override
    public ResultDTO getReportToRepairInfo(String serach, String page, String size) {
        ResultDTO resultDTO = new ResultDTO();

        try {
            JSONObject json = new JSONObject(serach);
            String existName = "0";

            String sqlexit = "select count(1) from report_torepair r where 1=1 ";

            String sql_w = "";//查询条件sql组合
            String sql_page = "";//分页组合

            Integer page_ok = Integer.parseInt(page);//将定义page、size的String类型转换成Integer类型
            Integer size_ok = Integer.parseInt(size);

            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok + 1) + "," + size + "";
            }

            if (json.has("member_id")) {
                sql_w += " AND r.member_id = '" + json.getString("member_id") + "'";
            }
            if (json.has("report_torepair_id")) {
                sql_w += " AND r.report_torepair_id = '" + json.getString("report_torepair_id") + "'";
            }
            if (json.has("isverify")) {
                sql_w += " AND r.isverify = '" + json.getString("isverify") + "'";
            }
//            else {
//                sql_w += " AND (isverify IS NULL OR isverify=0)";
//            }

            String sql_ok = sqlexit + sql_w + sql_page;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<ReportToRepairShowDTO> result = new ArrayList<ReportToRepairShowDTO>();

            if (!existName.equals("0")) {
                String sqlq = "SELECT r.report_torepair_id,r.report_name,r.report_reason,r.report_org,r.report_men,r.member_id,r.fail_resource," +
                        "r.create_time,r.isverify,r.repair_typeid,m.member_name,o.organization_name FROM report_torepair r LEFT OUTER JOIN kam_member m " +
                        "ON r.member_id = m.member_id LEFT OUTER JOIN organization o ON r.report_org = o.organization_id where 1=1  " + sql_w +
                        " ORDER BY create_time DESC" + sql_page;

                seresult = this.getReportingTo(sqlq);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++) {


                    ReportToRepairShowDTO reportToRepairShowDTO = new ReportToRepairShowDTO();

                    reportToRepairShowDTO.setReport_torepair_id(seresult.get(i)[1]);
                    reportToRepairShowDTO.setReport_name(seresult.get(i)[2]);
                    reportToRepairShowDTO.setReport_reason(seresult.get(i)[3]);
                    reportToRepairShowDTO.setReport_org(seresult.get(i)[4]);
                    reportToRepairShowDTO.setReport_men(seresult.get(i)[5]);
                    reportToRepairShowDTO.setMember_id(seresult.get(i)[6]);
                    reportToRepairShowDTO.setFail_resource(seresult.get(i)[7]);
                    reportToRepairShowDTO.setCreat_time(seresult.get(i)[8]);
                    reportToRepairShowDTO.setIsverify(seresult.get(i)[9]);
                    reportToRepairShowDTO.setMember_name(seresult.get(i)[11]);
                    reportToRepairShowDTO.setOrganization_name(seresult.get(i)[12]);

                    ResultDTO worklist=null,dispatch=null,repairType=null;
                    if(json.has("isverify")){
                        String state=json.getString("isverify");
                        worklist=workFlowResource.getWorkFlowInfo("{work_flow_formid:"+seresult.get(i)[1]+",work_flow_state:"+state+"}","1","20");
                    }else{
                        worklist=workFlowResource.getWorkFlowInfo("{work_flow_formid:"+seresult.get(i)[1]+"}","1","20");
                    }
                    reportToRepairShowDTO.setWorkflow(worklist.getValues());

//                    if (null != seresult.get(i)[5] && !"".equals(seresult.get(i)[5])) {
//                        jsonpeople = kamMemberResource.getUserListInfo("{id:" + seresult.get(i)[5] + "}", "1", "1");
//
//                        reportToRepairShowDTO.setMens(jsonpeople.getValues());
//                    }

//                    if (null != seresult.get(i)[4] && !"".equals(seresult.get(i)[4])) {
//                        organization = departmentResource.getDepartmentInfo("{organization_id:" + seresult.get(i)[4] + "}", "1", "1");
//                        reportToRepairShowDTO.setDepartments(organization.getValues());
//                    }

//                    if(seresult.get(i)[1] != null && ! seresult.get(i)[1].equals("")){
//
//                        suggestion=suggestionResource.getSuggestionInfo("{form_id:" + seresult.get(i)[1] + "}", "1", "100");
//                        reportToRepairShowDTO.setSuggestionShowDTOs(suggestion.getValues());
//                    }

                    if(seresult.get(i)[10]!=null&&!"".equals(seresult.get(i)[10])){
                        repairType = repairTypeResource.getRepairTypeInfo("{repair_typeid:"+seresult.get(i)[10]+"}","1","1");
                        reportToRepairShowDTO.setRepairTypeShowDTOs(repairType.getValues());
                    }

                    if(seresult.get(i)[1]!=null&&!"".equals(seresult.get(i)[1])){
                        dispatch = logisticsDispatchResource.getLogisticsDispatchInfo("{report_torepair_id:"+seresult.get(i)[1]+"}","1","999");
                        reportToRepairShowDTO.setLogisticsDispatchShowDTOs(dispatch.getValues());
                    }
                    result.add(reportToRepairShowDTO);

                }
            }
            if (seresult.size() != 0) {
                resultDTO.setStr(result.size() + "");
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
            resultDTO.setValues(result);

        } catch (JSONException e) {
            e.printStackTrace();

        }
        return resultDTO;
    }

    @Override
    public ResultDTO addReportToRepairInfo(ReportToRepairPullDTO reportToRepairPullDTO) {
        ResultDTO resultDTO = new ResultDTO();//构建返回对象


        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String existName = "";
        String report_torepair_id = reportToRepairPullDTO.getReport_torepair_id();
        if (report_torepair_id != null && !report_torepair_id.equals("")) {

            String sql = "select count(1) from report_torepair where report_torepair_id='" + report_torepair_id + "'";

            existName = getReportingToOne(sql);

            if (!existName.equals("0")) {
                return updateReportToRepairInfo(reportToRepairPullDTO);
            }
        }

        String QUERY = "";

        //表中查看时间设为空值
        QUERY += "insert into report_torepair(report_torepair_id,report_name,report_reason,repair_typeid,report_org,report_men,member_id,isverify,create_time) values" +
                " ('" + uuid + "','" + reportToRepairPullDTO.getReport_name() + "','" + reportToRepairPullDTO.getReport_reason() + "','" + reportToRepairPullDTO.getRepair_typeid() + "','" + reportToRepairPullDTO.getReport_org()
                + "','" + reportToRepairPullDTO.getReport_men() + "','" + reportToRepairPullDTO.getMember_id() + "','0','" + time + "')";
        int result = this.addReportingTo(QUERY);
        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(uuid);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
            //日志操作
            OperatorLogPullDTO operatorlogPullDTO = new OperatorLogPullDTO();
            operatorlogPullDTO.setWork_form_id(uuid);
            operatorlogPullDTO.setOperator_log_type("报修申请");
            operatorlogPullDTO.setOperator_log_title("报修申请");
            operatorlogPullDTO.setOperator_log_content(reportToRepairPullDTO.getReport_name());
            operatorlogPullDTO.setMember_id(reportToRepairPullDTO.getMember_id());
            operatorLogResource.addOperatorLogInfo(operatorlogPullDTO);

            //流程上报

            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(uuid);
            workFlowPullDTO.setWork_flow_type("report_torepair");
            workFlowPullDTO.setWork_flow_desc("后勤保修");
            workFlowPullDTO.setWork_flow_date(time);
            workFlowPullDTO.setWork_flow_order("0");
            workFlowPullDTO.setWork_flow_createid(reportToRepairPullDTO.getMember_id());
            workFlowPullDTO.setWork_flow_approval(reportToRepairPullDTO.getReport_people());
            workFlowPullDTO.setWork_flow_approval_organization_id(reportToRepairPullDTO.getWork_flow_approval_organization_id());
            workFlowPullDTO.setFlow_path_id("");
            workFlowPullDTO.setWork_flow_suggestion("");
            workFlowResource.addWorkFlowInfo(workFlowPullDTO);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;
    }

    @Override
    public ResultDTO updateReportToRepairInfo(ReportToRepairPullDTO reportToRepairPullDTO) {
        ResultDTO resultDTO = new ResultDTO();

        String QUERY = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        //更新sql语句
        QUERY += "update report_torepair set create_time ='" + time + "'";

        if (null != reportToRepairPullDTO.getReport_name() && !"".equals(reportToRepairPullDTO.getReport_name())) {
            QUERY += ",report_name ='" + reportToRepairPullDTO.getReport_name() + "'";
        }

        if (null != reportToRepairPullDTO.getReport_reason() && !"".equals(reportToRepairPullDTO.getReport_reason())) {
            QUERY += ",report_reason ='" + reportToRepairPullDTO.getReport_reason() + "'";
        }
        if (null != reportToRepairPullDTO.getReport_org() && !"".equals(reportToRepairPullDTO.getReport_org())) {
            QUERY += ",report_org ='" + reportToRepairPullDTO.getReport_org() + "'";
        }
        if (null != reportToRepairPullDTO.getReport_men() && !"".equals(reportToRepairPullDTO.getReport_men())) {
            QUERY += ",report_men ='" + reportToRepairPullDTO.getReport_men() + "'";
        }

        QUERY += " where report_torepair_id = '" + reportToRepairPullDTO.getReport_torepair_id() + "'";


        int result = this.addReportingTo(QUERY);
        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(reportToRepairPullDTO.getReport_torepair_id());
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");
        }
        return resultDTO;
    }

    @Override
    public ResultDTO deleteReportToRepairInfo(ReportToRepairPullDTO reportToRepairPullDTO) {
        //删除之前查询是否有记录
        String sql = "select count(1) from report_torepair where report_torepair_id ='" + reportToRepairPullDTO.getReport_torepair_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (!existName.equals("0")) {

            String QUERY = "";
            QUERY += "delete from report_torepair where report_torepair_id='" + reportToRepairPullDTO.getReport_torepair_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        if (result != 0) {

            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }

    @Override
    public ResultDTO getReportToRepairAn(String search) {
        ResultDTO resultDTO = new ResultDTO();

        List<String[]> seresult = new ArrayList<String[]>();

        String downloadUrl = "";

        String pdfDownLoadUrl = "";

        List<ReportToRepairStatisticsDTO> result = new ArrayList<ReportToRepairStatisticsDTO>();

        try {
            JSONObject json = new JSONObject(search);

//            String sql = "SELECT km2.member_name,km.member_name,o.organization_name,rt.repair_type_name," +
//                    "count(rtr.report_torepair_id) as count from report_torepair rtr " +
//                    "LEFT JOIN kam_member km " +
//                    "on km.member_id = rtr.member_id " +
//                    "LEFT JOIN repair_type rt " +
//                    "ON rt.repair_typeid = rtr.repair_typeid " +
//                    "LEFT JOIN kam_member km2 " +
//                    "ON km2.member_id = rtr.report_men " +
//                    "LEFT JOIN organization o " +
//                    "ON o.organization_id = rtr.report_org " +
//                    "where 1=1 ";

            String sql = "SELECT d.logistical_person,m.member_name,o.organization_name,r.repair_type_name,COUNT(d.logistics_dispatch_id) FROM logistics_dispatch d " +
                    "LEFT OUTER JOIN report_torepair rtr ON d.member_id = rtr.report_men AND d.report_torepair_id= rtr.report_torepair_id " +
                    "LEFT OUTER JOIN kam_member m ON rtr.member_id = m.member_id " +
                    "LEFT OUTER JOIN organization o ON m.organization_id = o.organization_id " +
                    "LEFT OUTER JOIN repair_type r ON d.dispatch_type = r.repair_typeid " +
                    "WHERE 1=1 ";

//            if(json.has("report_torepair_id")){
//                if(null != json.get("report_torepair_id") && !json.get("report_torepair_id").toString().isEmpty()){
//                    sql += "and d.report_torepair_id = '" + json.get("report_torepair_id").toString() + "' ";
//                }
//            }

            if(json.has("isverify")){
                if(null != json.get("isverify") && !json.get("isverify").toString().isEmpty()){
                    sql += "and rtr.isverify = '" + json.get("isverify").toString() + "' ";
                }
            }

            if(json.has("report_org_id")){
                if(null != json.get("report_org_id") && !json.get("report_org_id").toString().isEmpty()){
                    sql += "and rtr.report_org = '" + json.get("report_org_id").toString() + "' ";
                }
            }

            if(json.has("report_men")){
                if(null != json.get("report_men") && !json.get("report_men").toString().isEmpty()){
                    sql += "and rtr.report_men = '" + json.get("report_men").toString() + "' ";
                }
            }

            if(json.has("member_id")){
                if(null != json.get("member_id") && !json.get("member_id").toString().isEmpty()){
                    sql += "and rtr.member_id = '" + json.get("member_id").toString() + "' ";
                }
            }

            if(json.has("start_time")){
                if(null != json.get("start_time") && !json.get("start_time").toString().isEmpty()){
                    sql += "and rtr.create_time > '" + json.get("start_time").toString() + "' ";
                }

            }

            if(json.has("end_time")){
                if(null != json.get("end_time") && !json.get("end_time").toString().isEmpty()){
                    sql += "and rtr.create_time <' " + json.get("end_time").toString() + "' ";
                }
            }

            if(json.has("repair_typeid")){
                if(null != json.get("repair_typeid") && !json.get("repair_typeid").toString().isEmpty()){
                    sql += "and d.dispatch_type = '" + json.get("repair_typeid").toString() + "' ";
                }
            }

            if(json.has("logistical_person")){
                if(null != json.get("logistical_person") && !json.get("logistical_person").toString().isEmpty()){
                    sql += "and d.logistical_person LIKE '%" + json.get("logistical_person").toString() + "%'";
                }
            }

            sql += " GROUP BY d.dispatch_type,d.logistical_person ";

            seresult = this.getReportingTo(sql);

            for(int i = 0;i < seresult.size();i++){

                ReportToRepairStatisticsDTO reportToRepairStatisticsDTO = new ReportToRepairStatisticsDTO();

//                reportToRepairStatisticsDTO.setMember_id(seresult.get(i)[1] == null? "" : seresult.get(i)[1]);
                reportToRepairStatisticsDTO.setMember_name(seresult.get(i)[1] == null? "" : seresult.get(i)[1]);
                reportToRepairStatisticsDTO.setReport_name(seresult.get(i)[2] == null? "" : seresult.get(i)[2]);
                reportToRepairStatisticsDTO.setOrganization_name(seresult.get(i)[3] == null? "" : seresult.get(i)[3]);
                reportToRepairStatisticsDTO.setRepair_type_name(seresult.get(i)[4] == null? "" : seresult.get(i)[4]);
                reportToRepairStatisticsDTO.setCount(seresult.get(i)[5] == null? "" : seresult.get(i)[5]);

                result.add(reportToRepairStatisticsDTO);
            }

            if(json.has("export")){
                if(json.get("export").equals("1")){
                    String[] headers = {"维修人姓名", "报修人姓名", "保修部门名称", "报修类型", "统计数量"};
                    String title = "报修统计";
                    String filename = "报修统计表";
                    ExportExcel<ReportToRepairStatisticsDTO> exportExcel = new ExportExcel<ReportToRepairStatisticsDTO>();
                    downloadUrl = exportExcel.createExcelFile(exportExcel, title, headers, result, filename);

                    try {
                        pdfDownLoadUrl = ExportPDF.createPDFFile(seresult, title, headers, filename);
                    } catch (DocumentException e) {
                        e.printStackTrace();
                    }
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(result.size() >0){
            resultDTO.setStatus("90000");
            resultDTO.setStr(pdfDownLoadUrl);
            resultDTO.setValues(result);
            resultDTO.setDescritpion(downloadUrl);
        }
        else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.get_fail);
        }

        return resultDTO;
    }
}
